package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.job.vo.IotMsgNotifyData;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备表的查询Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-01
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {

    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private IoTDAClient client;


    @Transactional
    @Override
    public void registerDevice(DeviceDto dto) {
        //判断设备名称是否存在
        long count = count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()));
        if (count > 0) {
            throw new BaseException("设备名称'" + dto.getDeviceName() + "'已存在");
        }
        //判断设备标识码是否存在
        count = count(Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, dto.getNodeId()));
        if (count > 0) {
            throw new BaseException("设备标识码'" + dto.getNodeId() + "'已存在");
        }
        //判断同一位置是否绑定相同的产品
        count = count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(dto.getPhysicalLocationType() != null, Device::getPhysicalLocationType, dto.getPhysicalLocationType()));
        if (count > 0) {
            throw new BaseException("同一位置绑定相同产品");
        }
        //IoT设备注册
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice device = new AddDevice();
        device.setDeviceName(dto.getDeviceName());
        device.setProductId(dto.getProductKey());
        device.setNodeId(dto.getNodeId());
        // 秘钥设置,因为数据库表中也需要该字段
        AuthInfo authInfo = new AuthInfo();
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        authInfo.setSecret(secret);
        device.setAuthInfo(authInfo);
        request.setBody(device);
        AddDeviceResponse response;
        try {
            response = client.addDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 设备注册失败");
        }
        Device device1 = BeanUtil.toBean(dto, Device.class);
        device1.setSecret(secret);
        device1.setIotId(response.getDeviceId());
        this.save(device1);
    }

    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (ObjectUtils.isEmpty(device)) {
            return null;
        }
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response;
        try {
            response = client.showDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备详情失败");
        }
        DeviceDetailVo deviceVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        deviceVo.setBindingLocation(Long.valueOf(device.getBindingLocation()));
        deviceVo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
        if (StringUtils.isNotEmpty(activeTimeStr)) {
            // 日期时区转换
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            // 使用 hutool 提供的时区转换功能
            deviceVo.setActiveTime(LocalDateTimeUtil.offset(activeTime, 8, ChronoUnit.HOURS));

        }

        return deviceVo;
    }

    @Override
    public List<ProductVo> getAllProduct() {
        String jsonStr = redisTemplate.opsForValue().get(Constants.IOT_ALL_PRODUCT_LIST);
        if (StrUtil.isEmpty(jsonStr)) {
            return Collections.emptyList();
        }
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {

        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询设备影子失败");
        }
        List<DeviceShadowData> dataList = response.getShadow();
        if (CollectionUtil.isEmpty(dataList)) {
            return Collections.emptyList();
        }
        DeviceShadowProperties deviceShadowProperties = dataList.get(0).getReported();
        Object properties = deviceShadowProperties.getProperties();
        JSONObject jsonObject = JSONUtil.parseObj(properties);
        String eventTimeStr = deviceShadowProperties.getEventTime();
        // 把字符串转换为LocalDateTime
        LocalDateTime eventTimeLocalDateTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
        // 时区转换
        LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(eventTimeLocalDateTime);
        List<Map<String, Object>> list = new ArrayList<>();
        jsonObject.forEach((key, value) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("propertyName", key);
            map.put("value", value);
            map.put("eventTime", eventTime);
            list.add(map);
        });

        return list;
    }

    /**
     * 查询产品详情
     * @param productKey
     * @return
     */
    @Override
    public AjaxResult queryProduct(String productKey) {
        // 参数校验
        if(StringUtils.isEmpty(productKey)) {
            throw new BaseException("请输入正确的参数");
        }
        // 调用华为云IOT平台接口
        ShowProductRequest showProductRequest = new ShowProductRequest();
        showProductRequest.setProductId(productKey);
        ShowProductResponse response;

        try {
            response = client.showProduct(showProductRequest);
        } catch (Exception e) {
            throw new BaseException("查询产品详情失败");
        }
        // 判断是否存在服务数据
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if(CollUtil.isEmpty(serviceCapabilities)) {
            return AjaxResult.success(Collections.emptyList());
        }

        return AjaxResult.success(serviceCapabilities);
    }

    /**
     * 删除设备表的查询信息
     *
     * @param iotId 设备表的查询iotId
     * @return 结果
     */
    @Transactional
    @Override
    public void deleteDeviceOne(String iotId) {
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);
        DeleteDeviceResponse deleteDeviceResponse = client.deleteDevice(request);
        if (deleteDeviceResponse.getHttpStatusCode() != 204){
            throw new BaseException("物联网接口 - 删除设备失败");
        }
        this.remove(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
    }


    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        // 请求参数
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        // 设置条数
        listProductsRequest.setLimit(50);
        // 发起请求
        ListProductsResponse response = client.listProducts(listProductsRequest);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        // 存储到redis
        redisTemplate.opsForValue().set(Constants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(response.getProducts()));

    }
    /**
     * 修改设备表的查询
     *
     * @param device 设备表的查询
     * @return 结果
     */
    @Transactional
    @Override
    public void updateDevice(Device device) {
        //修改iot
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.setDeviceId(device.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.setDeviceName(device.getDeviceName());
        request.setBody(body);
        UpdateDeviceResponse updateDeviceResponse = client.updateDevice(request);
        if (updateDeviceResponse.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 修改设备失败");
        }
        updateById(device);
    }



    /**
     * 查询设备表的查询
     *
     * @param id 设备表的查询主键
     * @return 设备表的查询
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备表的查询列表
     *
     * @param device 设备表的查询
     * @return 设备表的查询
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备表的查询
     *
     * @param device 设备表的查询
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }


    /**
     * 批量删除设备表的查询
     *
     * @param ids 需要删除的设备表的查询主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }


    @Override
    public int deleteDeviceById(Long id) {
        return removeById(id) ? 1 : 0;
    }
}
